package com.gzwanchuang.xhgj.ui.web.ui;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.ValueCallback;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.protobuf.InvalidProtocolBufferException;
import com.gzwanchuang.architecture.utils.GsonUtils;
import com.gzwanchuang.architecture.utils.LogUtil;
import com.gzwanchuang.architecture.utils.Utils;
import com.gzwanchuang.xhgj.R;
import com.gzwanchuang.xhgj.app.App;
import com.gzwanchuang.xhgj.bean.BankCardOcrAddResult;
import com.gzwanchuang.xhgj.bean.IdCardOcrAddResult;
import com.gzwanchuang.xhgj.help.ImageHelper;
import com.gzwanchuang.xhgj.help.PermissionHelper;
import com.gzwanchuang.xhgj.help.UserHelper;
import com.gzwanchuang.xhgj.help.WebUtils;
import com.gzwanchuang.xhgj.net.NetworkManager;
import com.gzwanchuang.xhgj.net.interfaces.OnUpLoadCallBack;
import com.gzwanchuang.xhgj.proto.MemberOuterClass;
import com.gzwanchuang.xhgj.ui.MainActivity;
import com.gzwanchuang.xhgj.ui.TakeIdCardActivity;
import com.gzwanchuang.xhgj.ui.base.BaseActivity;
import com.gzwanchuang.xhgj.ui.LoginActivity;
import com.gzwanchuang.xhgj.ui.web.inteface.JavaScriptInterface;
import com.gzwanchuang.xhgj.ui.web.manager.MyChromeClient;
import com.gzwanchuang.xhgj.ui.web.manager.WebViewClientUtil;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.tencent.ocr.sdk.common.ISDKKitResultListener;
import com.tencent.ocr.sdk.common.ISdkOcrEntityResultListener;
import com.tencent.ocr.sdk.common.OcrSDKKit;
import com.tencent.ocr.sdk.common.OcrType;
import com.tencent.ocr.sdk.entity.BankCardOcrResult;
import com.tencent.ocr.sdk.entity.IdCardOcrResult;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;


public class WebViewActivity extends BaseActivity implements WebViewClientUtil.WebClientLoadListener,
        MyChromeClient.ProgressChangedListener, MyChromeClient.ReceivedTitleListener, MyChromeClient.WebFileChoseListener {


    //全局声明，用于记录选择图片返回的地址值
    private ValueCallback<Uri> uploadMessage;
    private ValueCallback valueCallback;
    private ValueCallback<Uri[]> uploadMessageAboveL;
    private static final String KEY_WEBURL = "KEY_WEBURL";
    public static final int BACK = 0x1fe;
    public static final int LOGIN = 0x4fe;
    public static final int GOTOCAPTURE = 0x3fe;
    public static final int TAKEPHOTOIDCARD = 0xffe;
    public static final int GOTOMAIN = 0x2fe;
    public static final int AUTOBANK = 0x5fe;
    //文件选择所需
    public final static int FILE_CHOOSER_RESULT_CODE_FOR_ANDROID_5 = 2;
    public final static int FILE_CHOOSER_RESULT_CODE = 1;// 表单的结果回调
    public final static int INTENT_PHONE = 5;// 表单的结果回调


    WebView webView;
    ImageView back;
    TextView refreshTv;
    TextView titleTv;
    ProgressBar prograssBar;
    LinearLayout refreshLayout;
    private MyChromeClient myChromeClient;
    private String url;
    public String methodName = "";

    private Handler jsInterfaceHandler = new JsInterfaceHandler(this);


    /**
     * 不带参数的地址
     *
     * @param context
     * @param url
     */
    public static void startActivity(Context context, String url) {
        if (context == null) return;
        Intent intent = new Intent(context, WebViewActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra(KEY_WEBURL, url);
        context.startActivity(intent);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_view);
        titleTv = findViewById(R.id.tv_title);
        webView = findViewById(R.id.web_View);
        refreshTv = findViewById(R.id.refresh_tv);
        prograssBar = findViewById(R.id.prograssBar);
        refreshLayout = findViewById(R.id.refreshLayout);
        refreshLayout.setOnClickListener(view -> {
            webView.loadUrl(url);
            refreshTv.setVisibility(View.GONE);
            prograssBar.setVisibility(View.VISIBLE);
        });
        back = findViewById(R.id.iv_back);
        back.setOnClickListener(view -> finish());
        initWebView();

    }

    //同步cookie
    private void syncCookie(Context context, String url) {
        try {
            CookieSyncManager.createInstance(context);
            CookieManager cookieManager = CookieManager.getInstance();
            cookieManager.setAcceptCookie(true);
            cookieManager.removeAllCookie();
            cookieManager.setCookie(url, "key=" + UserHelper.getCurrentToken());
            String newCookie = cookieManager.getCookie(url);
            if (newCookie != null) {
                LogUtil.d("Wang", "设置Cookie url=" + url + " ;   cookie=" + newCookie);
            }
        } catch (Exception e) {
            LogUtil.e("Wang: webView.syncCookie failed", e.toString());
        }
    }


    private void initWebView() {

        webView.addJavascriptInterface(new JavaScriptInterface(jsInterfaceHandler), "app");
        webView.setWebViewClient(new WebViewClientUtil(this, this));
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        webView.getSettings().setLoadsImagesAutomatically(true);// 加载网页中的图片
        webView.getSettings().setUseWideViewPort(true); //设置使用视图的宽端口
        webView.getSettings().setAllowFileAccess(true);// 可以读取文件缓存(manifest生效)
        webView.setWebChromeClient(myChromeClient = new MyChromeClient(this, this, this));
        myChromeClient.setBnWebFileChoseListener(this::getFile);
        // webView.setDownloadListener(new MyDownloadStart(this));//设置下载监听
        // webview 从Lollipop(5.0)开始webview默认不允许混合模式，https当中不能加载http资源，需要设置开启
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        url = getIntent().getStringExtra(KEY_WEBURL);
        if (!url.contains("http")) {
            url = ((App) (Utils.getApp())).getServiceHost() + getIntent().getStringExtra(KEY_WEBURL);
        }
//        if (UserHelper.isLogin() &&url.startsWith(BuildConfig.SERVERHEAD)) {
//            syncCookie(this, url);   //同步cookie 地址一定不能为空
//        }
        loadUrl();
    }

    private void loadUrl() {
        String newUrl;
        //统一拼接可
        if (UserHelper.isLogin()) {
            if (url.contains("?")) {
                newUrl = url + "&key=" + UserHelper.getCurrentToken() + "&isBack=true";
            } else {
                newUrl = url + "?key=" + UserHelper.getCurrentToken() + "&isBack=true";
            }
        } else {
            newUrl = url + "?isBack=true";
        }
        webView.loadUrl(newUrl);
        LogUtil.e("wang", "网页请求地址：" + newUrl);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
        switch (requestCode) {
            case FILE_CHOOSER_RESULT_CODE:
                if (null == myChromeClient.getmUploadMessage()) {
                    return;
                }
                myChromeClient.getmUploadMessage().onReceiveValue(result);
                myChromeClient.setmUploadMessage(null);
                break;
            case FILE_CHOOSER_RESULT_CODE_FOR_ANDROID_5:
                if (null == myChromeClient.getmUploadMessageForAndroid5())
                    return;
                if (result != null) {
                    myChromeClient.getmUploadMessageForAndroid5().onReceiveValue(new Uri[]{result});
                } else {
                    myChromeClient.getmUploadMessageForAndroid5().onReceiveValue(new Uri[]{});
                }
                myChromeClient.setmUploadMessageForAndroid5(null);
                break;
            case PictureConfig.CHOOSE_REQUEST:
                if (resultCode == RESULT_OK) {
                    List<LocalMedia> localMedias = PictureSelector.obtainMultipleResult(intent);
                    if (localMedias.size() >= 1) {
                        String compressPath = localMedias.get(0).getCompressPath();
                        upLoadImage(compressPath);
                    }
                }
                break;
            case 100:
                if (resultCode == RESULT_OK) {
                    String compressPath = intent.getAction();
                    upLoadImage(compressPath);
                }
                break;

        }
    }

    private void upLoadImage(String compressPath) {
        showProgress();
        ImageHelper.upLoadImage(compressPath, new ImageHelper.OnUpLoadImageCallBack() {
            @Override
            public void onSuccess(String images) throws InvalidProtocolBufferException {
                String[] temp = images.split(",");
                byte[] bytes = new byte[temp.length];
                for (int i = 0; i < temp.length; i++) {
                    bytes[i] = (byte) Integer.parseInt(temp[i]);
                }
                hideProgress();
                webView.loadUrl("javascript:" + methodName + "('" + MemberOuterClass.img_upload.parseFrom(bytes).getImg() + "')");
            }

            @Override
            public void onFail(String error) {
                hideProgress();
                showShortToast(error);
            }
        });
    }


    private void upLoadMultiImage(List<LocalMedia> localMedias) {

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (webView.canGoBack() && event.getKeyCode() == KeyEvent.KEYCODE_BACK
                && event.getRepeatCount() == 0) {
            webView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);

    }


    int errorCount;

    @Override
    public void loadFinished(String title, boolean isError) {


        prograssBar.setVisibility(View.GONE);


//        if (isError) {
//            if (errorCount == 2) {
//                refreshLayout.setVisibility(View.VISIBLE);
//                refreshTv.setVisibility(View.VISIBLE);
//                prograssBar.setVisibility(View.GONE);
//                webView.setVisibility(View.GONE);
//                errorCount = 0;
//            } else {
//                errorCount++;
//                loadUrl();
//            }
//        } else {
//            refreshLayout.setVisibility(View.GONE);
//            prograssBar.setVisibility(View.GONE);
//            webView.setVisibility(View.VISIBLE);
//        }
    }


    @Override
    public void getFile(ValueCallback valueCallback) {
        this.valueCallback = valueCallback;
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intent, INTENT_PHONE);
    }

    /*--------------------------------H5 调用原生--------------------------------*/

    private static class JsInterfaceHandler extends Handler {
        private WeakReference<Activity> weakRefActivity;
        private WebViewActivity context;

        public JsInterfaceHandler(WebViewActivity activity) {
            this.context = activity;
            weakRefActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            Activity activity = weakRefActivity.get();
            if (activity != null) {
                switch (msg.what) {
                    case GOTOMAIN:
                        Intent intents = new Intent(context, MainActivity.class);
                        context.startActivity(intents);
                        break;
                    case BACK:
                        activity.finish();
                        break;
                    case LOGIN:
                        UserHelper.loginOut();
                        Intent intent = new Intent(context, LoginActivity.class);
                        context.startActivity(intent);
                        break;
                    case GOTOCAPTURE:
                        captureWebView1(context, context.webView);
                        break;
                    case TAKEPHOTOIDCARD:
                        String s = (String) msg.obj;
                        String[] strings = s.split(",");
                        context.methodName = strings[0];
                        List<String> permission = new ArrayList<>();
                        permission.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
                        permission.add(Manifest.permission.CAMERA);
                        permission.add(Manifest.permission.READ_EXTERNAL_STORAGE);
                        PermissionHelper.getInstance().getPermissionGroup(context, new PermissionHelper.PermissionCallBack() {
                            @Override
                            public void onSuccess() {
                                if (strings[1].equals("3")) {
                                    ImageHelper.showImageChoose(context);
                                } else {
                                    Intent intent2 = new Intent(context, TakeIdCardActivity.class);
                                    intent2.setType(strings[1]);
                                    context.startActivityForResult(intent2, 100);
                                }
                            }

                            @Override
                            public void onFail() {
                                Toast.makeText(context, "获取权限失败", Toast.LENGTH_SHORT).show();
                            }
                        }, permission);
                        break;
                    case AUTOBANK:
                        String autoBank = (String) msg.obj;
                        String[] autoBanks = autoBank.split(",");
                        context.methodName = autoBanks[0];
                        String type = autoBanks[1];
                        OcrType ocrType = OcrType.IDCardOCR_FRONT;

                        switch (type) {
                            case "0":
                                ocrType = OcrType.IDCardOCR_FRONT;
                                break;
                            case "1":
                                ocrType = OcrType.IDCardOCR_BACK;
                                break;
                            case "2":
                                ocrType = OcrType.BankCardOCR;
                                break;
                        }
                        OcrSDKKit.getInstance().startProcessOcr(context, ocrType, null, new ISDKKitResultListener() {
                            @Override
                            public void onProcessSucceed(String response, String srcBase64Image, String requestId) {
                                Log.e("识别", "IdCardOcrResult:" + response); // OCR 识别成功 IdCardOcrResult
                                context.showProgress();
                                ImageHelper.upLoadImageBase64(srcBase64Image, new ImageHelper.OnUpLoadImageCallBack() {
                                    @Override
                                    public void onSuccess(String images) throws InvalidProtocolBufferException {
                                        context.hideProgress();
                                        String[] temp = images.split(",");
                                        byte[] bytes = new byte[temp.length];
                                        for (int i = 0; i < temp.length; i++) {
                                            bytes[i] = (byte) Integer.parseInt(temp[i]);
                                        }
                                        Log.e("图片地址", ":" + MemberOuterClass.img_upload.parseFrom(bytes).getImg()); // OCR 识别成功 IdCardOcrResult
                                        if (type.equals("2")) {
                                            BankCardOcrAddResult result = GsonUtils.deSerializedFromJson(response, BankCardOcrAddResult.class);
                                            result.setImageUrl(MemberOuterClass.img_upload.parseFrom(bytes).getImg());
                                            String jsonResult = GsonUtils.serializedToJson(result);
                                            context.webView.loadUrl("javascript:" + context.methodName + "('" + jsonResult + "')");
                                        } else {
                                            IdCardOcrAddResult result = GsonUtils.deSerializedFromJson(response, IdCardOcrAddResult.class);
                                            result.setImageUrl(MemberOuterClass.img_upload.parseFrom(bytes).getImg());
                                            String jsonResult = GsonUtils.serializedToJson(result);
                                            context.webView.loadUrl("javascript:" + context.methodName + "('" + jsonResult + "')");
                                        }

                                    }

                                    @Override
                                    public void onFail(String error) {

                                    }
                                });
                            }

                            @Override
                            public void onProcessFailed(String errorCode, String message, String requestId) {
                                context.showShortToast("识别失败，请重新识别");
                            }
                        });
                        break;
                }
            }
        }

    }

    @Override
    public void onProgressChanged(WebView view, int newProgress) {
        //进度显示

        if (newProgress > 90) {
            prograssBar.setVisibility(View.GONE);
        } else {
            prograssBar.setProgress(newProgress);
        }
    }

    @Override
    public void onReceivedTitle(WebView view, String title) {
        //网页加载完成 这里设置标题
        if (title.contains("http") || title.contains("网页无法打开") || title.contains(".com") || title.contains(".cn")) {
            return;
        }
        titleTv.setText(title);
    }


    /**
     * 对WebView进行截图
     *
     * @param webView
     * @return
     */
    public static void captureWebView1(Context context, WebView webView) {//可执行
//        PermissionHelper.getInstance().getPermission(context, new PermissionHelper.PermissionCallBack() {
//            @Override
//            public void onSuccess() {
//                Bitmap viewBitmap = SaveViewToImageUtil.getViewBitmap(webView);
//                String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "畅商服";
//                String fileName = System.currentTimeMillis() + ".jpg";
//                boolean b = ImageUtil.saveImageToGallery(context, viewBitmap, storePath, fileName);
//                if (b) {
//                    Toast.makeText(context, "截图保存成功，请在相册查看", Toast.LENGTH_SHORT).show();
//                }
//
//            }
//
//            @Override
//            public void onFail() {
//                Toast.makeText(context, "获取权限失败", Toast.LENGTH_SHORT).show();
//            }
//        }, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }

}
